package com.example.myapplication.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;

import androidx.annotation.Nullable;

import com.example.myapplication.R;
import com.example.myapplication.db.Data;
import com.example.myapplication.db.SQLiteManager;
import com.example.myapplication.waveform.DynamicLineChartManager;
import com.github.mikephil.charting.charts.LineChart;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class SensorFragment extends Fragment {
    private Switch switchButton;//用于开关节点
    private Context mContext = null;
    private Activity mActivity = null;
    private DynamicLineChartManager dynamicLineChartManager1;//用于以折线图形式显示传感器数据
    private List<Integer> list = new ArrayList<>(); //数据集合
    private List<String> names = new ArrayList<>(); //折线名字集合
    private List<Integer> colar = new ArrayList<>();//折线颜色集合
    private int[] colarArray;//用于存储颜色
    private String LoongSonID;//用于接收启动Activity时传入的龙芯节点名
    private String NodeName;//用于接收启动Activity时传入的传感器节点名
    private int sensorNum;//用于接收启动Activity时传入的传感器
    private int sensorIndex;
    private String sensorType;
    private byte[] sensorTypeHEX;
    private SQLiteManager helper;
    private SQLiteDatabase db;
    private final Timer timer = new Timer();//用于定时执行折线图数据更新
    Cursor cursor1;
    /**
     * 用于规避重复数据，因为数据上传时间是不固定的，但是定时器更新数据时间是固定的，所以每次查询最后一行数据时
     * 难免会查到上次的数据，所以通过记录上次成功查询的数据的索引，在这次查询时和上次的对比，就可以知道是不是新数据
     * */
    private int SensorDataIndex = 0;

    public SensorFragment(){

    }
    public static  SensorFragment newInstance(Bundle bundle){
        SensorFragment fragment = new SensorFragment();
        fragment.setArguments(bundle);

        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_sensor,container,false);
        mContext = getContext();
        mActivity = getActivity();

        colarArray = new int[7];
        colarArray[0] = Color.BLACK;
        colarArray[1] = Color.BLUE;
        colarArray[2] = Color.YELLOW;
        colarArray[3] = Color.RED;
        colarArray[4] = Color.GRAY;
        colarArray[5] = Color.GREEN;
        colarArray[6] = Color.LTGRAY;

        sensorTypeHEX = new byte[2];
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        helper = new SQLiteManager(mContext);
        if(getArguments() != null){
            LoongSonID = getArguments().getString(Data.COLUMN_Gateway);
            NodeName= getArguments().getString(Data.COLUMN_NodeName);
            sensorIndex = getArguments().getInt(Data.SENSORINDEX);
            String SensorTypeArray = getArguments().getString(Data.COLUMN_SensorTypeArray);
            sensorNum = getArguments().getInt(Data.COLUMN_SensorNum);
            try {
                String[] str = SensorTypeArray.split("_");
                for(int i = 0; i < str.length; i++) {
                    if(i == sensorIndex){
                        sensorType = str[i];
                        names.add(str[i]);
                        colar.add(colarArray[i]);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        /**
         * 初始化折线图，并设置折线、折线名称和折线颜色
         * */
        LineChart mChart = (LineChart) mActivity.findViewById(R.id.dynamic_chart1);
        dynamicLineChartManager1 = new DynamicLineChartManager(mChart, names, colar);
        names.clear();
        dynamicLineChartManager1.setYAxis(500, -20, 10);//设置折线图上下限和步进


        db = helper.getReadableDatabase();
        cursor1 = db.query(Data.SensorData_Table, null, Data.COLUMN_Gateway +"=? and " +
                Data.COLUMN_NodeName+"=?", new String[]{LoongSonID, NodeName}, null, null, null);

        int maxHistoryNum;
        if(cursor1.getCount() >=0 && cursor1.getCount() <= 10){
            maxHistoryNum = cursor1.getCount();
        }else {
            maxHistoryNum = Data.NumberHistoricalData;
        }

        boolean endFlag = true;
        int m = 0;
        List<Integer> listTemp = new ArrayList<>();
        /**
         * 初始化时显示历史数据
         * */
        if(cursor1.moveToPosition(cursor1.getCount() - maxHistoryNum)){
            do{
                if(m == maxHistoryNum){
                    endFlag = false;
                }else if(cursor1.getString(cursor1.getColumnIndexOrThrow(Data.COLUMN_NodeName)).equals(NodeName)) {
                    for (int j = 0; j < sensorNum; j++) {
                        if(j == sensorIndex){
                            listTemp.add((int) cursor1.getDouble(cursor1.getColumnIndexOrThrow(Data.COLUMN[7+2*j])));//更新数据
                        }
                    }
                    dynamicLineChartManager1.addEntry(listTemp);
                    listTemp.clear();
                    m++;
                }
            }while (cursor1.moveToNext() && endFlag);
        }
        cursor1.close();
        db.close();


        /**
         * 设置定时器，定时查询数据库是否有新数据，有的话更新在折线图和表格中
         * */
        timer.scheduleAtFixedRate(new TimerTask() {
            @SuppressLint("Range")
            @Override
            public void run() {
// TODO Auto-generated method stub

                db = helper.getReadableDatabase();
                cursor1 = db.query(Data.SensorData_Table, null, Data.COLUMN_Gateway +"=? and " +
                        Data.COLUMN_NodeName+"=?", new String[]{LoongSonID, NodeName}, null, null, null);

                boolean i = true;
                int m;
                if(cursor1.moveToLast()){
                    do{
                        m = cursor1.getInt(cursor1.getColumnIndex(Data.COLUMN_Index));
                        if(cursor1.getString(cursor1.getColumnIndex(Data.COLUMN_NodeName)).equals(NodeName) && m>SensorDataIndex){
                            for (int j = 0; j < sensorNum; j++){
                                if(j == sensorIndex){
                                    list.add((int) cursor1.getDouble(cursor1.getColumnIndex(Data.COLUMN[7 + 2 * j])));//更新数据
                                }
                            }
                            dynamicLineChartManager1.addEntry(list);
                            list.clear();
                            SensorDataIndex = cursor1.getInt(cursor1.getColumnIndex(Data.COLUMN_Index));//为下一轮做准备
                            i = false;
                        }
                    }while (cursor1.moveToPrevious() && i);
                }
                cursor1.close();
                db.close();
            }
        }, 100, 1000);
    }

}
